package cn.wingware.util;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;


public class HttpUtil {

	public static String PostUrl(String url,Map parms) {
		try {
		HttpClient httpClient = new HttpClient(); 
		PostMethod postMethod = new PostMethod(url);		
		if(null!=parms&&!parms.isEmpty()) {
		  NameValuePair[] data = new NameValuePair[parms.keySet().size()]; 
		  Iterator it = parms.entrySet().iterator(); 
		  int i=0;
		  while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next(); 
			Object key = entry.getKey(); 
			Object value = entry.getValue(); 
			data[i]=new NameValuePair(key.toString(),value.toString()); 
		    i++; 
		  }
		  postMethod.setRequestBody(data); 
		}
		httpClient.getParams().setContentCharset("utf-8"); 
		httpClient.setConnectionTimeout(4000);
		return postMethod.getResponseBodyAsString();
		} catch (Exception e) {
		  e.printStackTrace();
		  return "";
		}
	}
	
	public static String GetUrl(String url,Map parms) {
		try {
			HttpClient httpClient = new HttpClient(); 
			if(null!=parms&&!parms.isEmpty()) {
			  NameValuePair[] data = new NameValuePair[parms.keySet().size()]; 
			  Iterator it = parms.entrySet().iterator(); 
			  int i=0;
			  StringBuffer sb=new StringBuffer();
			  while (it.hasNext()) {
				Map.Entry entry = (Map.Entry) it.next(); 
				Object key = entry.getKey().toString(); 
				Object value = entry.getValue().toString();
				sb.append("&"+key+"="+value);
			  }
			  url=url+sb.toString();
			}
			GetMethod getMethod = new GetMethod(url);
			httpClient.setConnectionTimeout(4000);
			httpClient.executeMethod(getMethod); 
			return getMethod.getResponseBodyAsString();
			} catch (Exception e) {
			  e.printStackTrace();
			 return "";
			}
	}
	
	public static void main(String args[]) {
		HashMap map=new HashMap();
		map.put("p", "1");
		//String s=PostUrl("http://www.sohu.com/",map);
		//System.out.println(s);
	}
}
